package jrain.fw.json.fastjson;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;

import jrain.fw.core.json.JsonService;
import jrain.fw.core.service.Service;
import jrain.fw.core.service.ServiceConst;

@Service(name = "fastjson", group = ServiceConst.S_JSON_SERVICE, module = ServiceConst.M_JSON)
public class JsonFastJsonService implements JsonService {

	@Override
	public String toJson(Object object) {
		return JSON.toJSONString(object);
	}

	@Override
	public String toJson(Object object, Map<String, Object> cfg) {
		return JSON.toJSONString(object);
	}

	@Override
	public String toPageJson(Object object) {
		Map<String, Object> cfg = new HashMap<>();
		return toPageJson(object, cfg);
	}

	@Override
	public String toPageJson(Object object, Map<String, Object> cfg) {
		SerializeWriter out = new SerializeWriter();
		try {
			SerializerFeature.config(JSON.DEFAULT_GENERATE_FEATURE, SerializerFeature.QuoteFieldNames, true);

			JSONSerializer s = new JSONSerializer(out);
			s.getMapping().put(Long.class, new ObjectSerializer() {

				public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
					serializer.getWriter().write("\"");
					serializer.getWriter().write(String.valueOf(object));
					serializer.getWriter().write("\"");
				}
			});
			s.addFilter(new ValueFilter() {
				public Object process(Object object, String name, Object value) {
					if (value == null) {
						return "";
					}
					return value;
				}
			});
			s.write(object);
			return out.toString();
		} finally {
			out.close();
		}
	}

	@Override
	public List<Object> toList(String json) {
		return JSON.parseArray(json);
	}

	@Override
	public List<Object> toList(String json, Map<String, Object> cfg) {
		return JSON.parseArray(json);
	}

	@Override
	@SuppressWarnings("unchecked")
	public Map<String, Object> toMap(String json) {
		return JSON.parseObject(json, Map.class);
	}

	@Override
	@SuppressWarnings("unchecked")
	public Map<String, Object> toMap(String json, Map<String, Object> cfg) {
		return JSON.parseObject(json, Map.class);
	}

	@Override
	public <T> T toObject(String json, Class<T> t) {
		return JSON.parseObject(json, t);
	}

	@Override
	public <T> T toObject(String json, Class<T> t, Map<String, Object> cfg) {
		return JSON.parseObject(json, t);
	}

}
